#pragma once
#include "sock.hpp"
#include "Epoller.hpp"
#include "Util.hpp"
#include <functional>
#include <cassert>
#include <unordered_map>
#include "protocol.hpp"

namespace tcpserver
{
    class Connection;
    class TcpServer;
    static const uint16_t defalutport = 8080;
    static const int num = 64;
    using func_t = std::function<void(Connection *)>;
    // using handler_t =std::function<void(const std::string&)>;

    class Connection
    {
    public:
        Connection(TcpServer *tsp, int sock) : _sock(sock), _tsp(tsp) {}

        void Register(func_t r, func_t s, func_t e)
        {
            _recver = r;
            _sender = s;
            _excepter = e;
        }
        ~Connection() 
        {}

        void Close()
        {
            close(_sock);
        }

    public:
        int _sock;
        std::string _inbuffer;  // 输入缓冲区
        std::string _outbuffer; // 输出缓冲区

        func_t _recver;   // 从sock读
        func_t _sender;   // 向sock写
        func_t _excepter; // 处理sock IO时候的异常事件

        TcpServer *_tsp;
    };

    class TcpServer
    {
    public:
        TcpServer(func_t func, uint16_t port = defalutport) : _service(func), _port(port), _num(num), _revs(nullptr) {}
        void initserver()
        {
            // 创建sock
            _sock.Socket();
            _sock.Bind(_port);
            _sock.Listen();
            // 2.构建Epoll
            _epoller.Create();
            // 将listensock添加到epoll中
            AddConnection(_sock.Fd(), EPOLLIN | EPOLLET, std::bind(&TcpServer::Accepter, this, std::placeholders::_1), nullptr, nullptr);

            _revs = new struct epoll_event[num];
        }
        void Recver(Connection *conn)
        {
            logMessage(DEBUG, "Recver in");
            char buffer[1024];
            while (true)
            {
                ssize_t s = recv(conn->_sock, buffer, sizeof(buffer) - 1, 0);
                if (s > 0)
                {
                    buffer[s] = 0;
                    conn->_inbuffer += buffer;
                }
                else if (s == 0)
                {
                    if (conn->_excepter)
                        conn->_excepter(conn);
                    break;
                }
                else
                {
                    if (errno == EAGAIN || errno == EWOULDBLOCK)
                        break;
                    else if (errno == EINTR)
                        continue;
                    else
                    {
                        if (conn->_excepter)
                            conn->_excepter(conn);
                        break;
                    }
                }
            }

            _service(conn);
            logMessage(DEBUG, "Recver out");
            // logMessage(DEBUG,"%d -> %s ",conn->_sock,conn->_inbuffer.c_str());
        }

        void Sender(Connection *conn)
        {
            logMessage(DEBUG, "Sender in");
            while (true)
            {
                ssize_t s = send(conn->_sock, conn->_outbuffer.c_str(), conn->_outbuffer.size(), 0);
                if (s > 0)
                {
                    if (conn->_outbuffer.empty())
                    {
                        //EnableReadWrite(conn, true, false);
                        break;
                    }
                    else
                        conn->_outbuffer.erase(0, s);
                }
                else
                {
                    if (errno == EAGAIN || errno == EWOULDBLOCK)
                        break;
                    else if (errno == EINTR)
                        continue;
                    else
                    {
                        if (conn->_excepter)
                            conn->_excepter(conn);
                        break;
                    }
                }
            }
            // 如果没有发完数据，需要对对应的sock开启对写事件的关心，如果发完了，要关闭对写事件的关心
            if (!conn->_outbuffer.empty())
                conn->_tsp->EnableReadWrite(conn, true, true);
            else
                conn->_tsp->EnableReadWrite(conn, true, false);
        }
        void Execpter(Connection *conn)
        {
            logMessage(DEBUG,"Execpter begin");
            _epoller.Control(conn->_sock,0,EPOLL_CTL_DEL);
            conn->Close();
            _connections.erase(conn->_sock);
            logMessage(DEBUG,"关闭 %d 号文件描述符",conn->_sock);
            delete conn;
        }

        void Accepter(Connection *conn)
        {
            for (;;)
            {
                std::string clientip;
                uint16_t clientport;
                int err = 0;
                int sock = _sock.Accept(&clientip, &clientport, &err);
                if (sock > 0)
                {
                    AddConnection(sock, EPOLLIN | EPOLLET,
                                  std::bind(&TcpServer::Recver, this, std::placeholders::_1),
                                  std::bind(&TcpServer::Sender, this, std::placeholders::_1),
                                  std::bind(&TcpServer::Execpter, this, std::placeholders::_1));
                    logMessage(DEBUG, "get a new link, info: [%s : %d]", clientip.c_str(), clientport);
                }
                else
                {
                    if (err == EAGAIN || err == EWOULDBLOCK)
                        break;
                    else if (err == EINTR)
                        continue;
                    else
                        break;
                }
            }
        }

        void AddConnection(int sock, uint32_t events, func_t recver, func_t sender, func_t excepter)
        {
            // 1.为sock创建一个Connection对象,并添加到_connections中
            if (events & EPOLLET)
                Util::setNonBlock(sock);
            Connection *conn = new Connection(this, sock);

            // 2. 给对应的sock设置回调函数
            conn->Register(recver, sender, excepter);

            // 3. 将sock与它要关心的事件注册到epoll中，让epoll帮我们关心
            bool r = _epoller.AddEvent(sock, events);
            assert(r);
            (void)r;
            // 4. 将它添加到_connections
            _connections.insert(std::make_pair(sock, conn));
        }

        bool IsConnectionExists(int sock)
        {
            auto it = _connections.find(sock);
            return it != _connections.end();
        }

        void Loop(int timeout)
        {
            int n = _epoller.Wait(_revs, _num, timeout);
            for (int i = 0; i < n; ++i)
            {
                int sock = _revs[i].data.fd;
                uint32_t events = _revs[i].events;

                // 将所有的异常问题，全部转化成为读写问题
                if (events & EPOLLERR)
                    events |= (EPOLLIN | EPOLLOUT);
                if (events & EPOLLHUP)
                    events |= (EPOLLIN | EPOLLOUT);

                if ((events & EPOLLIN) && _connections[sock]->_recver && IsConnectionExists(sock))
                    _connections[sock]->_recver(_connections[sock]);
                if (events & EPOLLOUT && _connections[sock]->_sender && IsConnectionExists(sock))
                    _connections[sock]->_sender(_connections[sock]);
            }
        }

        void EnableReadWrite(Connection *conn, bool readalbe, bool writeable)
        {
            uint32_t event = (readalbe ? EPOLLIN : 0) | (writeable ? EPOLLOUT : 0);
            _epoller.Control(conn->_sock, event, EPOLL_CTL_MOD);
        }

        // 事件派发器
        void Dispath()
        {
            int timeout = -1;
            while (true)
            {
                Loop(timeout);
                logMessage(DEBUG, "timeout....");
            }
        }

        ~TcpServer() {}

    private:
        uint16_t _port;
        Sock _sock;
        Epoller _epoller;
        std::unordered_map<int, Connection *> _connections;
        struct epoll_event *_revs;
        int _num;
        // handler_t _handler;
        func_t _service;
    };
}